import { getExcelData } from '@/axios/api/outlook/createEmail';
import { ElNotification } from 'element-plus';
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();

export default function () {


    // 显示通知消息
    function showMessage(type: number, message: string) {
        const title = type === 200 ? 'Success' : 'Error';
        ElNotification({
            title: title,
            message: message,
            type: type === 200 ? 'success' : 'error',
        });
    }

    async function importExcelData() {
        try {
            counterStore.excelData_pinia = [];
            counterStore.path = '';
            const res: any = await getExcelData();
            if (res.code == 200) {
                counterStore.excelData_pinia = res.data;
                counterStore.path = res.path;
            } else {
                counterStore.excelData_pinia = [];
            }
            showMessage(res.code, res.message);
        } catch (err: any) {
            showMessage(err.code, err.message);
        }
      };


    // 创建邮件
    let socket: WebSocket | null = null;
    const MESSAGE_TYPE_COMPLETE = '邮件创建完成';
    async function createEmailData(multipleSelection: any[]) {
        const WEBSOCKET_URL = 'ws://localhost:8000/email/ws';

        try {

            const EmailData: any[] = [];

            if (multipleSelection.length === 0) {
                showMessage(400, 'Please select contacts');
                return;
            }
            counterStore.mailCount = multipleSelection.length;
            counterStore.flag = true;
            multipleSelection.forEach(item => {
                EmailData.push({
                    "con": item.con,
                    "country": item.country,
                    "eu": item.eu,
                    "bat": item.bat,
                    "ph": item.ph,
                    "reci": item.reci,
                });
            });


            // 确保 WebSocket 连接存在且处于打开状态
            if (socket === null || socket.readyState !== WebSocket.OPEN) {
                socket = new WebSocket(WEBSOCKET_URL);
            }

            // 等待 WebSocket 打开
            await whenWebSocketOpen(socket);

            // 发送数据
            const message = JSON.stringify({
                "data": EmailData,
                "excelpath": counterStore.path
            });
            socket?.send(message);

            // 等待消息处理完成
            await waitForAllMessagesToBeProcessed();

            // 所有消息处理完成后，设置 flag 为 false
            counterStore.flag = false;

        } catch (err: any) {
            counterStore.flag = false;
            showMessage(err.code, err.message);
        }
    }

    async function whenWebSocketOpen(socket: WebSocket | null): Promise<void> {
        return new Promise((resolve, reject) => {
            if (!socket) {
                reject('WebSocket is null');
                return;
            }
            socket.onopen = () => resolve();
            socket.onerror = (event: Event) => reject('WebSocket error: ' + event);
        });
    }

    async function waitForAllMessagesToBeProcessed() {
        return new Promise<void>((resolve, reject) => {
            // 必须检查 socket 是否存在
            if (!socket) {
                console.error('WebSocket is not initialized.');
                return;
            }

            socket.onmessage = (event: MessageEvent) => {
                if (event.data.startsWith('00')) {
                    counterStore.mailCount--;
                    const con = event.data;
                    const index = counterStore.excelData_pinia.findIndex((item: any) => item.con === con);
                    if (index !== -1) {
                        counterStore.excelData_pinia.splice(index, 1);
                    }
                } else if (event.data === MESSAGE_TYPE_COMPLETE) {
                    // console.log('All messages processed.');
                    resolve();
                } else {
                    // 处理其它异常情况
                    counterStore.flag = false;
                    showMessage(204, event.data);
                    reject();
                }
            };
        });
    }


    return {
        importExcelData,
        createEmailData
    }
};